//
//  UserAccountModel.swift
//  weibo项目
//
//  Created by mac on 16/1/14.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountModel: NSObject {
    
    var userAccount:UserAccount?
    override init() {
        userAccount = UserAccount.loaUserAccount()
        super.init()
    }
    
    func login()->Bool{
    
    return userAccount?.access_token != nil
    
    }
    
    func loadAccessToken(code: String){
        let  urlString = "https://api.weibo.com/oauth2/access_token"
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        let parameters = ["client_id": client_id ,"redirect_uri":redirect_uri, "client_secret":client_secret,"code":code,"grant_type":"authorization_code"]
        
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //        把数据access_token和uid取出来
            //        当字典的数据为空的时候
            guard let dict = result as? [String : AnyObject] else{
                
                print("数据的格式不正确")
                
                return
                
            }
            
            //     let access_token = dict["access_token"] as! String
            //        let uid = dict["uid"] as! String
            let account = UserAccount(dict: dict)
            
            self.loadData(account)
            
            print("++++",result)
            }) { (_, error) -> Void in
                print(error)
        }
        
        
        
    }
    
    func loadData(account:UserAccount){
        //    发送网络请求获取数据  获取用户信息
        //    print("-=-=-=",access_token,uid)
        let urlString = "https://api.weibo.com/2/users/show.json"
        //        获取afn对象
        let AFN = AFHTTPSessionManager()
        let parameters = ["access_token":account .access_token!,"uid":account.uid!]
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //            判断结果是否为空
            guard let dict = result as? [String : AnyObject] else{
                
                return
            }
            account.name = dict["name"] as! String
            account.avatar_larger = dict["avatar_large"] as! String
            account.saveData()
            
            print("*******",account)
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
}
